﻿using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using ViewModel.User;
using EPIClientRssWP7.AuthenticationService;
using serviceMaker.UserManagementService;
using GalaSoft.MvvmLight.Command;

namespace ViewModel.User
{
    public class AuthentificationViewModel : UserViewModelBase
    {

        public AuthentificationViewModel()
        {
            Authenticate = new RelayCommand(ExecuteAuthentication, CanExecuteAuthentication);
            Register = new RelayCommand(ExecuteRegister, CanExecuteRegister);
            UserBind = new DataUser();
            UserBind = clientInfos.CurrentUser;
        }

        private string messageAuth;
        public string MessageAuth
        {
            get {return messageAuth;}
            set
            {
               if (messageAuth != value)
                {
                    messageAuth = value;
                    RaisePropertyChanged("MessageAuth");
                }
            }
        }

        private DataUser userBind;
        public DataUser UserBind
        { 
			get
			{
				return userBind;
			}
            set
            {
                if (userBind != value)
                {
                    userBind = value;
                    RaisePropertyChanged("UserBind");
                }
            }
        }

        #region CommandAuthenticate
        public ICommand Authenticate
        { get; set; }

     



        private void LoginServer()
        {
            try
            {
                AuthService.CookieContainer = clientInfos.cc;
                AuthService.LoginCompleted += new EventHandler<EPIClientRssWP7.AuthenticationService.LoginCompletedEventArgs>(AuthenticateComplete);
                AuthService.LoginAsync(new LoginRequest(userBind.email, userBind.password, "", true));
                //UserService.authenticateUserCompleted += new EventHandler<serviceMaker.UserManagementService.authenticateUserCompletedEventArgs>(AuthenticateComplete);
                //UserService.authenticateUserAsync(new authenticateUserRequest(userBind));
            }
            catch (InvalidOperationException e)
            {
                Console.WriteLine(e.Message);
                Console.WriteLine(e.Data);
                Console.WriteLine(e.StackTrace);
            }
        }



        private void ExecuteAuthentication()
        {
            try
            {
                UserService.isServerAvailableCompleted += IsAvailableAnswer;
                UserService.isServerAvailableAsync(new isServerAvailableRequest());
            }
            catch (Exception e)
            {
                MessageAuth = "Unable to reach the server :: " + e.Message;
            }
        }

        public void IsAvailableAnswer(object sender, isServerAvailableCompletedEventArgs arg)
        {
            if (arg != null && arg.Result.isServerAvailableResult == true)
                LoginServer();
            else
                MessageAuth = "Unable to reach the server :: " + arg.Error != null ? arg.Error.ToString() : "";
        }

        private bool CanExecuteAuthentication()
        {
            return true;
        }

        public void AuthenticateComplete(object sender, LoginCompletedEventArgs arg)
        {
            if (arg == null)
                throw new ArgumentNullException("Authenticate return null");
 //          
            if (arg.Result != null && arg.Result.LoginResult == true && arg.Error == null)
            {
                UserService.CookieContainer = clientInfos.cc;
                UserService.getUserProfileByLoginCompleted += new EventHandler<getUserProfileByLoginCompletedEventArgs>(UserInfoReceived);
                UserService.getUserProfileByLoginAsync(new getUserProfileByLoginRequest(userBind.email));

            }
            else
                MessageAuth = "Invalid Email or Password";
        }
   

        public void UserInfoReceived(object sender, getUserProfileByLoginCompletedEventArgs arg)
        {
            if (arg != null && arg.Result != null && arg.Result.getUserProfileByLoginResult != null)
            {
                 
                DataUser user = arg.Result.getUserProfileByLoginResult;
                clientInfos.CurrentUser = user;
                clientInfos.Authenticate = true;
                UserBind = user;
                MessageAuth = "Bonjour " + userBind.name;
                SaveId(UserBind.email, UserBind.password);
                clientInfos.SaveCookie(clientInfos.cc);
                DirectoryService.getRootDirectoryIdCompleted += (obj, arg2) =>
                {
                    if (arg2 != null && arg2.Error == null && arg2.Result != null)
                        clientInfos.userRootDirectory = arg2.Result.getRootDirectoryIdResult;
                };
                DirectoryService.getRootDirectoryIdAsync(new serviceMaker.DirectoryService.getRootDirectoryIdRequest(clientInfos.CurrentUser.id));
                
            }
            this.NavigateToHome();
        }
        #endregion

        private string resultRegister;
        public string ResultRegister
        {
            get
            {
                return resultRegister;
            }
            set 
            {
                if (value != resultRegister)
                {
                    resultRegister = value;
                    RaisePropertyChanged("ResultRegister");
                }
            }
        }

        #region Command Register


        public ICommand Register
        { get; set; }

        private void ExecuteRegister()
        {
            ServiceUserManagementClient service = new ServiceUserManagementClient();
            service.registerUserCompleted += (obj, arg) =>
            {
                if (arg != null && arg.Error == null)
                {
                    if (arg.Result.registerUserResult == "OK" && Authenticate.CanExecute(this) == true)
                    {
                        ResultRegister = "Registering ended properly.\r\nWaiting for redirection";
                        if (CanExecuteAuthentication() == true)
                            ExecuteAuthentication();
                    }
                    else
                        ResultRegister = arg.Result.registerUserResult;
                }
                else
                    ResultRegister = arg != null ? arg.Error.Message : "";
            };
            UserBind.name = "";
            if (UserBind.password != null && UserBind.password != "" && UserBind.email != null && UserBind.email != "")
                service.registerUserAsync(new registerUserRequest(UserBind));
            else
                ResultRegister = "You need to set the email field and the password field";
        }

        private bool CanExecuteRegister()
        {
            return true;
        }



        #endregion

        public virtual bool NavigateToHome()
      {
          if (clientInfos.Authenticate == true)
            return true;
          return false;
      }


        public virtual void SaveId(string email, string password)
        {
            return;
        }

        public virtual bool GetId()
        {

            return false;
        }

        public bool DoesNeedAuthentication()
        {
            if (GetId() == true)
            {
                AuthService.CookieContainer = clientInfos.cc;
                AuthService.ValidateUserCompleted += (obj, arg) =>
                {
                    if (arg != null && arg.Error == null)
                        if (arg.Result != null && arg.Result.ValidateUserResult == true)
                        {
                            AuthService.LoginCompleted += (obj2, arg2) =>
                            {
                                if (arg2.Result != null && arg2.Result.LoginResult == true)
                                {
                                    UserService.CookieContainer = clientInfos.cc;
                                    UserService.getUserProfileByLoginCompleted += new EventHandler<getUserProfileByLoginCompletedEventArgs>(UserInfoReceived);
                                    UserService.getUserProfileByLoginAsync(new getUserProfileByLoginRequest(userBind.email));
                                }
                                else
                                {
                                    MessageAuth += "Cannot Authenticate auto";
                                    NavigateToHome();
                                }
                            };
                            AuthService.LoginAsync(new LoginRequest(UserBind.email, UserBind.password, "", true));
                        }
                        else
                           NavigateToHome();
                };
                AuthService.ValidateUserAsync(new ValidateUserRequest(UserBind.email, UserBind.password, ""));
            }
            else
                NavigateToHome();
            return true;
        }
    }
};